package com.minimalist.lindi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.config.mybatis.bo.PageResp;
import com.minimalist.common.entity.basic.enums.RespEnum;
import com.minimalist.common.entity.basic.enums.StatusEnum;
import com.minimalist.common.entity.basic.vo.file.FileUpdateStatusVO;
import com.minimalist.common.entity.lindi.po.LindiActivity;
import com.minimalist.common.entity.lindi.vo.activity.LindiActivityQueryVO;
import com.minimalist.common.entity.lindi.vo.activity.LindiActivityVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.utils.TextUtil;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.mapper.LindiActivityMapper;
import com.minimalist.lindi.service.LindiActivityService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 林地指标交易平台_活动内容表 服务层实现。
 *
 * @author 11987
 * @since 2025-06-12
 */
@Service
public class LindiActivityServiceImpl extends ServiceImpl<LindiActivityMapper, LindiActivity> implements LindiActivityService{

    @Autowired
    private LindiActivityMapper mapper;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addActivity(LindiActivityVO activityVO){
        LindiActivity activity = BeanUtil.copyProperties(
                activityVO, LindiActivity.class);
        //活动ID
        long activityId = UnqIdUtil.uniqueId();
        activity.setActivityId(activityId);
        //内容处理 -> 编码
        activity.setActivityContent(TextUtil.encode(activityVO.getActivityContent()));
        //插入
        int insertCount = mapper.insert(activity, true);
        Assert.isTrue(insertCount > 0
                , () -> new BusinessException(RespEnum.FAILED.getDesc()));
        //活动相关文件处理
        fileStatusHandler(null, activityVO, StatusEnum.STATUS_1.getCode());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteActivityByActivityId(Long activityId){
        //查询活动
        LindiActivity activity = mapper.selectActivityByActivityId(activityId);
        Assert.notNull(activity, () -> new BusinessException("活动不存在"));
        //活动相关文件处理
        fileStatusHandler(null
                , BeanUtil.copyProperties(activity, LindiActivityVO.class)
                , StatusEnum.STATUS_0.getCode());
        //删除活动
        mapper.deleteActivityByActivityId(activityId);
    }

    @Override
    public void updateActivityByActivityId(LindiActivityVO activityVO){
        //查询活动
        LindiActivity activity = mapper.selectActivityByActivityId(activityVO.getActivityId());
        Assert.notNull(activity, () -> new BusinessException("活动不存在"));
        LindiActivity newActivity = BeanUtil.copyProperties(activityVO, LindiActivity.class);
        //内容处理 -> 编码
        newActivity.setActivityContent(TextUtil.encode(newActivity.getActivityContent()));
        //修改
        mapper.updateActivityByActivityId(newActivity);
        //活动相关文件处理
        fileStatusHandler(activity, BeanUtil.copyProperties(newActivity, LindiActivityVO.class), null);
    }

    @Override
    public PageResp<LindiActivityVO> getPageActivityList(LindiActivityQueryVO queryVO){
        //分页查询
        Page<LindiActivity> activityPage = mapper.selectPageActivityList(queryVO);
        //数据转换
        List<LindiActivityVO> activityVOList = BeanUtil.copyToList(activityPage.getRecords()
                , LindiActivityVO.class);
        activityVOList.forEach(item -> item.setActivityContent(""));
        return new PageResp<>(activityVOList, activityPage.getTotalRow());
    }

    @Override
    public LindiActivityVO getActivityByActivityId(Long activityId){
        LindiActivity activity = mapper.selectActivityByActivityId(activityId);
        //内容 -> 解码
        activity.setActivityContent(TextUtil.decode(activity.getActivityContent()));
        Assert.notNull(activity, () -> new BusinessException("活动不存在"));
        return BeanUtil.copyProperties(activity, LindiActivityVO.class);
    }

    @Override
    public PageResp<LindiActivityVO> getWebsiteActivityList(LindiActivityQueryVO queryVO){
        // 前台网站只查询状态为1（已发布）的活动
        queryVO.setStatus(StatusEnum.STATUS_1.getCode());
        Page<LindiActivityVO> activityPage = mapper.selectWebsiteActivityList(queryVO);
        List<LindiActivityVO> activityVOList = activityPage.getRecords();
        return new PageResp<>(activityVOList, activityPage.getTotalRow());
    }

    @Override
    public LindiActivityVO getWebsiteActivityDetail(Long activityId){
        LindiActivity activity = mapper.selectWebsiteActivityDetail(activityId);
        Assert.notNull(activity, () -> new BusinessException("活动不存在或未发布"));

        //内容 -> 解码
        activity.setActivityContent(TextUtil.decode(activity.getActivityContent()));
        return BeanUtil.copyProperties(activity, LindiActivityVO.class);
    }

    /**
     * 修改活动相关的文件信息
     *
     * @param oldActivity 活动(旧)
     * @param newActivity 活动(新)
     * @param fileStatus  文件状态
     */
    private void fileStatusHandler(LindiActivity oldActivity, LindiActivityVO newActivity, Integer fileStatus){
        //活动插入、删除的文件处理
        if (ObjectUtil.isNull(oldActivity)){
            //处理富文本编辑器中的图片，富文本内容解码
            String decodeOldContent = TextUtil.decode(newActivity.getActivityContent());
            List<String> imgUrlList = TextUtil.getImgUrlByRichText(decodeOldContent);
            if (CollectionUtil.isNotEmpty(imgUrlList)){
                //将富文本中的图片的状态置为已使用
                FileUpdateStatusVO fileUpdateStatusVO = new FileUpdateStatusVO(StpUtil.getLoginIdAsLong(), imgUrlList, fileStatus);
                fileFeignClient.updateStatusByFileUrl(fileUpdateStatusVO);
            }
        } else{
            //旧活动富文本中的图片
            String decodeOldContent = TextUtil.decode(oldActivity.getActivityContent());
            List<String> oldContentImgUrlList = TextUtil.getImgUrlByRichText(decodeOldContent);
            //将旧活动富文本中的图片状态置为未使用
            if (CollectionUtil.isNotEmpty(oldContentImgUrlList)){
                FileUpdateStatusVO fileUpdateStatusVO = new FileUpdateStatusVO(
                        StpUtil.getLoginIdAsLong(), oldContentImgUrlList
                        , StatusEnum.STATUS_0.getCode());
                fileFeignClient.updateStatusByFileUrl(fileUpdateStatusVO);
            }
            //新活动富文本中的图片
            String decodeNewContent = TextUtil.decode(newActivity.getActivityContent());
            List<String> newContentImgUrlList = TextUtil.getImgUrlByRichText(decodeNewContent);
            //将新活动富文本中的图片状态置为已使用
            if (CollectionUtil.isNotEmpty(newContentImgUrlList)){
                FileUpdateStatusVO fileUpdateStatusVO = new FileUpdateStatusVO(
                        StpUtil.getLoginIdAsLong(), newContentImgUrlList
                        , StatusEnum.STATUS_1.getCode());
                fileFeignClient.updateStatusByFileUrl(fileUpdateStatusVO);
            }
        }
    }
}